package com.huashizhaoxi.lionapp.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.gson.Gson;
import com.huashizhaoxi.lionapp.entity.Address;
import com.huashizhaoxi.lionapp.entity.Result;
import com.huashizhaoxi.lionapp.entity.User;
import com.huashizhaoxi.lionapp.service.UserService;
import com.huashizhaoxi.lionapp.utils.HttpClientUtils;
import com.huashizhaoxi.lionapp.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;


@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;


    private JwtUtils jwtUtils;

    private HttpClientUtils httpClientUtils;

    private String appid = "wx6d4ed04668f5e6f7";

    private String appSecret = "cf5eae0e8d08d9d7554a349ccf89ff66";

    private String grant_type = "authorization_code";

    private String url = "https://api.weixin.qq.com/sns/jscode2session";




    @GetMapping("/all/{pageNum}")
    public Result getAllUser(@RequestHeader("mytoken") String token,
                             @PathVariable(value = "pageNum") Integer pageNum) {
        Map<String,Object> map1 = jwtUtils.parseJwt(token);
        if(map1 == null) {
            return Result.error("token无效");
        }
        User user = userService.getUserByOpenId((String) map1.get("open_id"));
        boolean isChief = user.getRole() == 2;
        if(!isChief) {
            return Result.error("权限不足");
        }
        PageHelper.startPage(pageNum, 7);
        List<User> userList = userService.getAllUser();
        if (userList != null) {
            PageInfo list = new PageInfo(userList);
            Map map = new HashMap();
            map.put("list",list.getList());
            map.put("size",list.getSize());
            map.put("total",list.getTotal());
            return Result.success("获取用户列表成功", map);
        }else{
            return Result.error("获取用户列表失败");
        }
    }

    @GetMapping("/search/{text}/{pageNum}")
    public Result searchUser(@PathVariable("text") String text,
                             @PathVariable(value = "pageNum") Integer pageNum,
                             @RequestHeader("mytoken") String token) {
        Map<String,Object> map1 = jwtUtils.parseJwt(token);
        if(map1 == null) {
            return Result.error("token无效");
        }
        User user = userService.getUserByOpenId((String) map1.get("open_id"));
        boolean isChief = user.getRole() == 2;
        if(!isChief) {
            return Result.error("权限不足");
        }
        PageHelper.startPage(pageNum, 7);
        List<User> userList = userService.searchUser(text);
        if(userList != null) {
            PageInfo list = new PageInfo(userList);
            Map map = new HashMap();
            map.put("list",list.getList());
            map.put("size",list.getSize());
            map.put("total",list.getTotal());
            return Result.success("搜索用户成功", map);
        } else {
            return Result.error("搜索用户失败");
        }
    }

    @GetMapping("/login/{code}")
    public Result login(@PathVariable("code") String code) throws Exception {
        if (code.isEmpty()) {
            return Result.error("登录凭证为空");
        }
//        System.out.println(code);
        String url1 = url + "?appid=" + appid + "&secret=" + appSecret + "&js_code=" + code + "&grant_type=" + grant_type;
//        System.out.println(url1);
        try{
            String res = httpClientUtils.get(url1);
            System.out.println(res);
            Gson gson = new Gson();
            //将JSON格式的字符串转换为一个map集合
            HashMap mapAccessToken = gson.fromJson(res, HashMap.class);
            String access_token = (String) mapAccessToken.get("session_key");
            String openid = (String) mapAccessToken.get("openid");
            User user = userService.getUserByOpenId(openid);
            if(user == null){
                User user1 = new User();
                user1.setOpen_id(openid);
                user1.setRole(0);
                user1.setNickname("花狮朝夕用户");
                userService.addUser(user1);
                user = userService.getUserByOpenId(openid);
            }
            Map<String,Object> map = new HashMap<>();
            map.put("open_id",openid);
            map.put("id",user.getId());
            String token = jwtUtils.generateJwt(map);
            Map map1 = new HashMap();
            map1.put("id",user.getId());
            map1.put("token",token);
            map1.put("role",user.getRole());
            map1.put("nickname",user.getNickname());

            return Result.success("登录成功", map1);
        }catch(Exception e){
            e.printStackTrace();
            return Result.error("登录失败");
        }

    }

    // 账密登录
//    @PostMapping("/login")
//    public Result login(@RequestBody User user) {
//        String username = user.getUsername();
//        User userTmp = userService.getUserByUsername(username);
//        if(userTmp == null) {
//            return Result.error("用户不存在");
//        } else {
//            System.out.println(userTmp.getPassword());
//            System.out.println(user.getPassword());
//            if(userTmp.getPassword().equals(user.getPassword())) {
//                Map<String,Object> map = new HashMap<>();
//                map.put("username",username);
//                map.put("password",userTmp.getPassword());
//                map.put("id",userTmp.getId());
//                String token = jwtUtils.generateJwt(map);
//                Map map1 = new HashMap();
//                map1.put("id",userTmp.getId());
//                map1.put("token",token);
//                map1.put("role",userTmp.getRole());
//                map1.put("nickname",userTmp.getNickname());
//                return Result.success("登录成功", map1);
//            } else {
//                return Result.error("密码错误");
//            }
//        }
//    }
//
//    @PostMapping("/register")
//    public Result register(@RequestBody User user) {
//        String username = user.getUsername();
//        User userTmp = userService.getUserByUsername(username);
//        if(userTmp != null) {
//            return Result.error("用户已存在");
//        } else {
//            user.setRole(0);
//            user.setNickname("花狮朝夕用户");
//            int res = userService.addUser(user);
//            if(res == 1) {
//                Map<String,Object> map = new HashMap<>();
//                map.put("username",user.getUsername());
//                map.put("password",user.getPassword());
//                map.put("id",user.getId());
//                String token = jwtUtils.generateJwt(map);
//                Map map1 = new HashMap();
//                map1.put("id",user.getId());
//                map1.put("token",token);
//                map1.put("role",user.getRole());
//                map1.put("nickname",user.getNickname());
//                return Result.success("注册成功", map1);
//            } else {
//                return Result.error("注册失败");
//            }
//        }
//    }

    // 通过token获取自己大致的信息
    @GetMapping("/myroughinfo")
    public Result getMyInfo(@RequestHeader("mytoken") String token) {
        Map<String,Object> map = jwtUtils.parseJwt(token);
        if(map == null) {
            return Result.error("token无效");
        } else {
            User user = userService.getUserByOpenId((String) map.get("open_id"));
            if(user == null) {
                return Result.error("用户不存在");
            } else {
                Map map1 = new HashMap();
                map1.put("personality_front",user.getPersonality_front());
                map1.put("role",user.getRole());
                map1.put("nickname",user.getNickname());
                return Result.success("获取个人信息成功", map1);
            }
        }
    }

    // 通过token获取自己除了密码外的详细信息
    @GetMapping("/myinfo")
    public Result getDetailMyInfo(@RequestHeader("mytoken") String token) {
        Map<String,Object> map = jwtUtils.parseJwt(token);
        if(map == null) {
            return Result.error("token无效");
        } else {
            User user = userService.getUserByOpenId((String) map.get("open_id"));
            if(user == null) {
                return Result.error("用户不存在");
            } else {
                Map map1 = new HashMap();
                map1.put("id",user.getId());
                map1.put("nickname",user.getNickname());
                map1.put("role",user.getRole());
                map1.put("personality_front",user.getPersonality_front());
                map1.put("phone",user.getPhone());
                map1.put("email",user.getEmail());
                map1.put("create_time",user.getCreate_time());
                return Result.success("获取个人信息成功", map1);
            }
        }
    }

    // 获取我的权限等级
    @GetMapping("/rolelevel")
    public Result getRoleLevel(@RequestHeader("mytoken") String token){
        Map<String,Object> map = jwtUtils.parseJwt(token);
        if(map == null){
            return Result.error("token无效");
        } else {
            String username = (String) map.get("username");
            User user = userService.getUserByOpenId((String) map.get("open_id"));
            if (user == null) {
                return Result.error("用户不存在");
            } else {
                return Result.success("获取权限成功", user.getRole());
            }
        }
    }

    // 修改我的个人信息
    @PostMapping("/modifymyinfo")
    public Result modifyMyInfo(@RequestHeader("mytoken") String token, @RequestBody User user) {
        Map<String,Object> map = jwtUtils.parseJwt(token);
        if(map == null) {
            return Result.error("token无效");
        } else {
            String openId = (String) map.get("open_id");
            user.setOpen_id(openId);
            int res = userService.modifyUser(user);
            if(res == 1) {
                return Result.success("修改个人信息成功",null);
            } else {
                return Result.error("修改个人信息失败");
            }
        }
    }

    // 查询所有地址
    @GetMapping("/myaddress")
    public Result getAllAddress(@RequestHeader("mytoken") String token) {
        Map<String,Object> map = jwtUtils.parseJwt(token);
        if(map == null) {
            return Result.error("token无效");
        } else {
            User user = userService.getUserByOpenId((String) map.get("open_id"));
            if(user == null) {
                return Result.error("用户不存在");
            } else {
                List<Address> addressList = userService.getAllAddress(user.getId());
                return Result.success("获取地址列表成功", addressList);
            }
        }
    }

    @PostMapping("/addaddress")
    public Result addAddress(@RequestHeader("mytoken") String token, @RequestBody Address address) {
        Map<String,Object> map = jwtUtils.parseJwt(token);
        if(map == null) {
            return Result.error("token无效");
        } else {
            User user = userService.getUserByOpenId((String) map.get("open_id"));
            if(user == null) {
                return Result.error("用户不存在");
            } else {
                address.setUser_id(user.getId());
                int res = userService.addAddress(address);
                if(res == 1) {
                    return Result.success("添加地址成功", null);
                } else {
                    return Result.error("添加地址失败");
                }
            }
        }
    }

    @PutMapping("/modifyaddress")
    public Result modifyAddress(@RequestHeader("mytoken") String token, @RequestBody Address address) {
        Map<String,Object> map = jwtUtils.parseJwt(token);
        if(map == null) {
            return Result.error("token无效");
        } else {
            User user = userService.getUserByOpenId((String) map.get("open_id"));
            if(user == null) {
                return Result.error("用户不存在");
            } else {
                int res = userService.modifyAddress(address);
                if(res == 1) {
                    return Result.success("修改地址成功", null);
                } else {
                    return Result.error("修改地址失败");
                }
            }
        }
    }

    @PostMapping("/changerole")
    public Result changeRole(@RequestHeader("mytoken") String token,@RequestBody User user){
        Map<String,Object> map = jwtUtils.parseJwt(token);
        if(map == null){
            return Result.error("token无效");
        } else {
            User user1 = userService.getUserByOpenId((String) map.get("open_id"));
            if(user1 == null){
                return Result.error("用户不存在");
            } else {
                if(user1.getRole() == 2){
                    int res = userService.changeRole(user);
                    if(res == 1){
                        return Result.success("修改权限成功",null);
                    } else {
                        return Result.error("修改权限失败");
                    }
                } else {
                    return Result.error("权限不足");
                }
            }
        }
    }

}
